package com.roncoo.ysq.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.roncoo.ysq.config.CustomizeException;
import com.roncoo.ysq.config.MyCustomizeErrorCode;
import com.roncoo.ysq.entity.Adv;
import com.roncoo.ysq.dao.AdvMapper;
import com.roncoo.ysq.service.IAdvService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuanshuaiqiang
 * @since 2021-03-24
 */
@Service
public class AdvServiceImpl extends ServiceImpl<AdvMapper, Adv> implements IAdvService {

    @Resource
    private AdvMapper advMapper;

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.bucketName}")
    private String bucketName;

    //文件存储目录
    @Value("${aliyun.filehost}")
    private String filedir;


    @Override
    public IPage<Adv> findAll(Page page, Adv adv) {
        QueryWrapper<Adv> advQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(adv.getAdvTitle())){
            advQueryWrapper.like("adv_title",adv.getAdvTitle());
        }
        if (adv.getStatusId()!=null){
            advQueryWrapper.eq("status_id",adv.getStatusId());
        }
        Page page1 = advMapper.selectPage(page, advQueryWrapper);
        return page1;
    }

    /**
     * 前台轮播
     * @return
     */
    @Override
    public List<Adv> findByStatus() {
        QueryWrapper<Adv> advQueryWrapper = new QueryWrapper<>();
        advQueryWrapper.eq("status_id",0);
        List<Adv> advs = advMapper.selectList(advQueryWrapper);
        return advs;
    }


    /**
     * 上传图片
     * @param file
     * @return
     */
    @Override
    public String getPath(MultipartFile file) {
        String path="";
        //Map map=new HashMap();
        // System.out.println(file.isEmpty());
        // System.out.println(file.getSize());
        //获取文件的名字
        //System.out.println(file.getOriginalFilename());
        //从文件名截取后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //获取随机码
        UUID uuid = UUID.randomUUID();
        //将随机码和后缀拼接，组成的新的文件名
        String objectName = uuid + suffix;
        try {
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            //
            //oss-cn-beijing.aliyuncs.com
            //String endpoint = "oss-cn-shanghai.aliyuncs.com";
            // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
            //String accessKeyId = "LTAI5tFs2ayNUqexEyBXGkjA";
            //String accessKeySecret = "OsMWpQ9i6D7DweFASF2TedhNRknly9";
            //String bucketName = "ysq-bucket";

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, inputStream);
            //System.out.println(putObjectResult.toString());
            // 关闭OSSClient。
            ossClient.shutdown();
            path = "https://" + bucketName + "." + endpoint + "/" + objectName;
            //文件上传需要的参数  msg code data
            if (path!=null && path!=""){
                return path;
            }else {
                return null;
            }
        } catch (IOException e) {
            throw new CustomizeException(MyCustomizeErrorCode.IMAGE_UPLOAD_FAIL);
        }
    }

}
